import axios from 'axios'
import qs from 'qs'

const baseUrl = '/'
axios.defaults.headers['callback-url'] = window.location.href // window.location.href;

// 设置请求头
axios.interceptors.request.use(
  config => {
    // console.log(config);
    if (config.method === 'get') {
      config.params = {
        _t: Date.parse(new Date()) / 1000,
        ...config.params
      }
    }
    return config
  },
  error => {
    // 发送请求错误操作
    return Promise.reject(error)
  }
)
// 处理返回值
axios.interceptors.response.use(
  response => {
    const { data } = response
    const { code } = data
    const { message } = data
    // debugger
    switch (code) {
      case 200:
        return data
      default:
        return Promise.reject(message)
    }
  },
  error => {
    let originalRequest = error.config
    // 超时统一处理
    if (error.code === 'ECONNABORTED' && error.message.indexOf('timeout') !== -1 && !originalRequest._retry) {
      return Promise.reject('timeout')
    }
    return Promise.reject(error)
  }
)
/**
 * ** Get(Post) 请求封装
 * @ url 请求地址
 * @ data 发送的数据
 * @ sources 用于停止当前请求
 * @ timeout 请求超时时间
 * @ apiUrl 修改默认 baseUrl
 * */
export const Get = function({
  url = '',
  data = {},
  sources = [],
  timeout = 1000 * 10,
  headers = {},
  apiUrl = ''
} = {}) {
  // 配置请求地址
  url = apiUrl ? apiUrl + url : baseUrl + url
  // console.log(url);

  sources = Array.isArray(sources) ? sources : [] // 存储请求信息,用于停止请求
  var CancelToken = axios.CancelToken // 停止请求使用
  var token = new CancelToken(function executor(cancel) {
    sources.push(cancel)
  })
  data = data || {}
  //  console.log(axios.defaults.headers.callback = window.location.href);
  if (JSON.stringify(data) === '{}') {
    return axios.get(url, {
      cancelToken: token, // 停止请求使用
      timeout: timeout, // 请求超时设
      headers
    })
  } else {
    return axios.get(url + '?' + qs.stringify(data), {
      cancelToken: token,
      timeout: timeout,
      headers
    })
  }
}

export const Post = function({
  url = '',
  data = {},
  sources = [],
  timeout = 1000 * 10,
  headers = {},
  apiUrl = ''
} = {}) {
  // 配置请求地址
  url = apiUrl ? apiUrl + url : baseUrl + url
  sources = Array.isArray(sources) ? sources : [] // 存储请求信息,用于停止请求
  var CancelToken = axios.CancelToken // 停止请求使用
  var token = new CancelToken(function executor(cancel) {
    sources.push(cancel)
  })

  data = data || {}
  return axios.post(url, data, {
    cancelToken: token,
    timeout: timeout,
    headers
  })
  // console.log((axios.defaults.headers.callback = window.location.href));
}

export const $Http = axios
